//
//  YCAlertView1.m
//  CustomByWindow
//
//  Created by tangkexiong on 16/1/4.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCAlertView1.h"

#define kDlgWidth 270.f
#define kBtnHeight 44.f
#define kBtnMaxHeight (kBtnHeight*4)
#define kTitleFont 17.f
#define kMessageFont 15.f
#define kAnimationDuration 0.3f
#define kViewAlpha 0.9f

#pragma mark - YCAlertViewActionCell

@implementation YCAlertView1ActionCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        [self _buildViews];
    }
    
    return self;
}

- (void)_buildViews {
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, kBtnHeight)];
    bgView.alpha = kViewAlpha;
    bgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bgView];
    bgView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:bgView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1.f constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:bgView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeLeading multiplier:1.f constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:bgView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTrailing multiplier:1.f constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:bgView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeBottom multiplier:1.f constant:0]];
    
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, kBtnHeight)];
    _nameLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.textColor = [UIColor blackColor];
    _nameLabel.font = [UIFont systemFontOfSize:kTitleFont];
    [self.contentView addSubview:_nameLabel];
    _nameLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_nameLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1.f constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_nameLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeLeading multiplier:1.f constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_nameLabel attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTrailing multiplier:1.f constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_nameLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeBottom multiplier:1.f constant:0]];
}

@end

#pragma mark - YCAlertView1

@interface YCAlertView1()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    UIWindow *_window;
    
    NSMutableArray *_btnTitleArray;
    
    UIView *_bgView;
    UIView *_dlgView;
    UIScrollView *_headView;
    UIView *_headBgView;
    UILabel *_titleLabel;
    UILabel *_messageLabel;
    UICollectionView *_btnView;
    UIView *_btnHeaderView;
    UIView *_btnFooterView;
}

@end

@implementation YCAlertView1

- (instancetype)initWithTitle:(NSString *)title Message:(NSString *)message Delegate:(id<YCAlertView1Delegate>)delegate ButtonTitles:(NSString *)btnTitle, ... {
    self = [super init];
    
    if (self) {
        self.title = title;
        self.message = message;
        self.delegate = _delegate;
        
        _btnTitleArray = [[NSMutableArray alloc] init];
        va_list args;
        va_start(args, btnTitle);
        if (btnTitle) {
            [_btnTitleArray addObject:btnTitle];
            while ((btnTitle=va_arg(args, NSString *))) {
                [_btnTitleArray addObject:btnTitle];
            }
        }
        va_end(args);
    }
    
    return self;
}

- (void)dealloc {
    [self _removeNotificationObserver];
}

- (void)_buildViews {
    self.backgroundColor = [UIColor clearColor];
    
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    _bgView.backgroundColor = [UIColor blackColor];
    _bgView.alpha = 0.f;
    [self addSubview:_bgView];
    
    _dlgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, 0)];
    _dlgView.backgroundColor = [UIColor clearColor];
    _dlgView.clipsToBounds = YES;
    _dlgView.layer.cornerRadius = 10.f;
    [self addSubview:_dlgView];
    
    _headView = nil;
    if (_title || _message) {
        _headView = [[UIScrollView alloc] init];
        _headView.backgroundColor = [UIColor clearColor];
        [_dlgView addSubview:_headView];
    
        if (_title) {
            _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, 0)];
            _titleLabel.numberOfLines = 0;
            _titleLabel.textColor = [UIColor blackColor];
            _titleLabel.textAlignment = NSTextAlignmentCenter;
            _titleLabel.font = [UIFont boldSystemFontOfSize:kTitleFont];
            _titleLabel.text = _title;
            [_headView addSubview:_titleLabel];
        }
        
        
        if (_message) {
            _messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, 0)];
            _messageLabel.numberOfLines = 0;
            _messageLabel.textAlignment = NSTextAlignmentCenter;
            _messageLabel.textColor = [UIColor blackColor];
            _messageLabel.font = [UIFont systemFontOfSize:kMessageFont];
            _messageLabel.text = _message;
            [_headView addSubview:_messageLabel];
        }
        
        _headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _headBgView.backgroundColor = [UIColor whiteColor];
        _headBgView.alpha = kViewAlpha;
        [_headView insertSubview:_headBgView atIndex:0];
    }
    
    _btnView = nil;
    if (_btnTitleArray.count > 0) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _btnView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, 0) collectionViewLayout:layout];
        _btnView.showsHorizontalScrollIndicator = NO;
        _btnView.showsVerticalScrollIndicator = NO;
        [_btnView registerClass:[YCAlertView1ActionCell class] forCellWithReuseIdentifier:@"cell"];
        _btnView.backgroundColor = [UIColor clearColor];
        _btnView.delegate = self;
        _btnView.dataSource = self;
        [_dlgView addSubview:_btnView];
    }
    
    _btnHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, 0)];
    _btnHeaderView.backgroundColor = [UIColor whiteColor];
    _btnHeaderView.alpha = kViewAlpha;
    [_btnView insertSubview:_btnHeaderView atIndex:0];
    
    _btnFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDlgWidth, 0)];
    _btnFooterView.backgroundColor = [UIColor whiteColor];
    _btnFooterView.alpha = kViewAlpha;
    [_btnView insertSubview:_btnFooterView atIndex:0];
    
    [self _deviceOrientationDidChange:nil];
}

- (void)_layoutViews {
    _dlgView.transform = CGAffineTransformIdentity;
    
    CGSize screenSizeRefer = [UIScreen mainScreen].bounds.size;
    CGSize screenSizeReal = [self _getScreenSize];
    self.frame = CGRectMake(0, 0, screenSizeReal.width, screenSizeReal.height);
    
    _bgView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    
    CGFloat headViewHeight = 0.f;
    if (_title || _message) {
        headViewHeight += 10.f;
        
        CGFloat titleHeight = 0.f;
        if (_title) {
            titleHeight = [_title boundingRectWithSize:CGSizeMake(kDlgWidth-30.0f, 0)
                                               options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                            attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:kTitleFont]}
                                               context:nil].size.height;
            _titleLabel.frame = CGRectMake(15.0f, headViewHeight, kDlgWidth-30.0f, titleHeight);
        }
        
        CGFloat messageHeight = 0.f;
        if (_message) {
            messageHeight = [_message boundingRectWithSize:CGSizeMake(kDlgWidth-30.0f, 0)
                                                 options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                              attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kMessageFont]}
                                                 context:nil].size.height;
            messageHeight += 20.f;
            _messageLabel.frame = CGRectMake(15.0f, headViewHeight+titleHeight, kDlgWidth-30.0f, messageHeight);
        }
        
        headViewHeight += titleHeight + messageHeight;
        
        _headBgView.frame = CGRectMake(0, 0, kDlgWidth, headViewHeight);
        
        _headView.contentSize = CGSizeMake(kDlgWidth, headViewHeight);
    }
    
    CGFloat btnViewHeight = 0.f;
    if (_btnTitleArray.count > 0) {
        if (_btnTitleArray.count > 2) {
            btnViewHeight = kBtnHeight * _btnTitleArray.count + 0.5f * _btnTitleArray.count;
        } else {
            btnViewHeight = kBtnHeight + 0.5f;
        }
        
        _btnView.frame = CGRectMake(0, headViewHeight, kDlgWidth, btnViewHeight);
        [_btnView.collectionViewLayout invalidateLayout];
    }
    
    CGFloat MAXDLGHEIGHT = screenSizeRefer.height-20.f;
    if (btnViewHeight > kBtnMaxHeight) {
        if (headViewHeight + btnViewHeight > MAXDLGHEIGHT) {
            if (headViewHeight + kBtnMaxHeight > MAXDLGHEIGHT) {
                if (_headView) {
                    _headView.frame = CGRectMake(0, 0, kDlgWidth, MAXDLGHEIGHT-kBtnMaxHeight);
                }
                if (_btnView) {
                    _btnView.frame = CGRectMake(0, MAXDLGHEIGHT-kBtnMaxHeight, kDlgWidth, kBtnMaxHeight);
                }
                
                _dlgView.frame = CGRectMake((screenSizeReal.width-kDlgWidth)/2, (screenSizeReal.height-MAXDLGHEIGHT)/2, kDlgWidth, MAXDLGHEIGHT);
            } else {
                if (_headView) {
                    _headView.frame = CGRectMake(0, 0, kDlgWidth, headViewHeight);
                }
                if (_btnView) {
                    _btnView.frame = CGRectMake(0, headViewHeight, kDlgWidth, MAXDLGHEIGHT-headViewHeight);
                }
                
                _dlgView.frame = CGRectMake((screenSizeReal.width-kDlgWidth)/2, (screenSizeReal.height-MAXDLGHEIGHT)/2, kDlgWidth, MAXDLGHEIGHT);
            }
        } else {
            if (_headView) {
                _headView.frame = CGRectMake(0, 0, kDlgWidth, headViewHeight);
            }
            if (_btnView) {
                _btnView.frame = CGRectMake(0, headViewHeight, kDlgWidth, btnViewHeight);
            }
            
            _dlgView.frame = CGRectMake((screenSizeReal.width-kDlgWidth)/2, (screenSizeReal.height-headViewHeight-btnViewHeight)/2, kDlgWidth, headViewHeight+btnViewHeight);
        }
    } else {
        if (headViewHeight + btnViewHeight > MAXDLGHEIGHT) {
            if (_headView) {
                _headView.frame = CGRectMake(0, 0, kDlgWidth, MAXDLGHEIGHT-btnViewHeight);
            }
            if (_btnView) {
                _btnView.frame = CGRectMake(0, MAXDLGHEIGHT-btnViewHeight, kDlgWidth, btnViewHeight);
            }
            
            _dlgView.frame = CGRectMake((screenSizeReal.width-kDlgWidth)/2, (screenSizeReal.height-MAXDLGHEIGHT)/2, kDlgWidth, MAXDLGHEIGHT);
        } else {
            if (_headView) {
                _headView.frame = CGRectMake(0, 0, kDlgWidth, headViewHeight);
            }
            if (_btnView) {
                _btnView.frame = CGRectMake(0, headViewHeight, kDlgWidth, btnViewHeight);
            }
            
            _dlgView.frame = CGRectMake((screenSizeReal.width-kDlgWidth)/2, (screenSizeReal.height-headViewHeight-btnViewHeight)/2, kDlgWidth, headViewHeight+btnViewHeight);
        }
    }
    
    _btnHeaderView.frame = CGRectMake(0, -300, kDlgWidth, 300);
    _btnFooterView.frame = CGRectMake(0, btnViewHeight, kDlgWidth, 300);
}

#pragma mark - NSNotification

- (void)_addNotificationObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_deviceOrientationDidChange:) name:UIApplicationDidChangeStatusBarOrientationNotification
                                               object:nil];
}

- (void)_removeNotificationObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIApplicationDidChangeStatusBarOrientationNotification
                                                  object:nil];
}

- (void)_deviceOrientationDidChange:(NSNotification *)notification {
    [self _layoutViews];
    
    [UIView beginAnimations:nil context:nil];
    
    [UIView setAnimationDuration:[UIApplication sharedApplication].statusBarOrientationAnimationDuration];

    _dlgView.transform = [self _getTransformMakeRotationByOrientation:[UIApplication sharedApplication].statusBarOrientation];
    
    [UIView commitAnimations];
}

- (CGAffineTransform)_getTransformMakeRotationByOrientation:(UIInterfaceOrientation)orientation {
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        return CGAffineTransformMakeRotation(-M_PI_2);
    } else if (orientation == UIInterfaceOrientationLandscapeRight) {
        return CGAffineTransformMakeRotation(M_PI_2);
    } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
        return CGAffineTransformMakeRotation(M_PI);
    } else {
        return CGAffineTransformIdentity;
    }
}

- (CGSize)_getScreenSize {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
        CGFloat tmp = screenWidth;
        screenWidth = screenHeight;
        screenHeight = tmp;
    }
    
    return CGSizeMake(screenWidth, screenHeight);
}

#pragma mark - control

- (void)show {
    [self _addNotificationObserver];
    
    [self _buildViews];
    
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = 440.f;
    _window.rootViewController = [[UIViewController alloc] init];
    [_window addSubview:_window.rootViewController.view];
    [_window addSubview:self];
    [_window makeKeyAndVisible];
    
    [self _showAnimation];
}

- (void)_dimiss {
    [self _dismissAnimation];
}

- (void)_showAnimation {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        _bgView.alpha = 0.5;
    } completion:^(BOOL finished) {
        
    }];
    
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = kAnimationDuration;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 0.9f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [_dlgView.layer addAnimation:popAnimation forKey:nil];
}

- (void)_dismissAnimation {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        _bgView.alpha = 0.0;
        _dlgView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _btnTitleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YCAlertView1ActionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.nameLabel.text = _btnTitleArray[indexPath.row];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_btnTitleArray.count > 2) {
        return CGSizeMake(kDlgWidth, kBtnHeight);
    } else if (_btnTitleArray.count > 1) {
        return CGSizeMake((kDlgWidth-0.5f)/2, kBtnHeight);
    } else {
        return CGSizeMake(kDlgWidth, kBtnHeight);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0.5f, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.5;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(alertView1:didClickedAtIndex:)]) {
        [self.delegate alertView1:self didClickedAtIndex:indexPath.row];
    }
    
    [self _dimiss];
}

@end
